/*
 * Created on Wed Jun 06 2018 by Ronnie Ren (zhaosong.ren) from Accenture
 *
 * Copyright (c) 2018 DingXing information & technology limited company.
 */

import { Injectable } from "@angular/core";
import { SqliteService } from "../../services/sqliteDB/sqlite.service";
import { AttachmentDto } from "../dto/attachment.dto";
import { Attachment } from "../transform/attachment";
import { JsonMappingUtil } from "../json-mapping-util";
import { Observable } from "rxjs";
import { CurdService } from "./curd.service";
import { SyncUtilService } from "../../services/offline/sync.util.service";
import { SyncStatus } from "../sync-status";
import {UtilsService} from "../../services/utils.services";


@Injectable()
export class AttachmentService {

  constructor(
    private sqliteService: SqliteService,
    private curdService: CurdService,
    private syncUtilService: SyncUtilService,
    private utilsService: UtilsService
  ) {

  }

  addImg(attachments: Array<Attachment>) {
    let attachmentDtos = attachments.map((attachment) => {
      let attachmentDto = new AttachmentDto();
      attachmentDto.id = attachment.id;
      attachmentDto.path = attachment.path;
      attachmentDto.attachmentName = attachment.attachmentName;
      return attachmentDto;
    });
    this.curdService.addRow({ dto: AttachmentDto, mapObj: Attachment }, attachmentDtos);
  }

  addAttachment(obj) {
    if (Array.isArray(obj)) {
      obj.forEach((item, index) => {
        this.add(item);
      });
    } else {
      this.add(obj);
    }
  }

  add(obj) {
    let AttachmentDtoObj = new AttachmentDto();
    let test = new Attachment(obj);
    JsonMappingUtil.MappingAllProp(test, AttachmentDtoObj);
    // console.log(UserDtoObj);
    this.sqliteService.add(AttachmentDtoObj)
      .then((results) => {
        console.log(JSON.stringify(results));
      })
      .catch((e) => {
        console.error(e);
      });
  }

  fetchAttachmentByIds(ids: Array<string>): Observable<Array<Attachment>> {
    return this.curdService.observableFetchObjects(AttachmentDto, null, [{ id: ids }])
      .map(
        (attachmentDtos: Array<AttachmentDto>) => {
          console.log(attachmentDtos);
          return attachmentDtos
            .map((attachmentDto) => {
              let attachment = this.syncUtilService.toObjectFromDto(attachmentDto, Attachment);
              console.log(attachment, "----fetchAttachmentByIds");
              return attachment;
            });
        }
      );
  }

  downloadAttchmentsAndSave(attachmentIds) {
    return this.utilsService.downByIdArray(attachmentIds)
      .flatMap((downArray) => {
          return this.syncUtilService.saveAttachment(this.AttachmentThumbnailIdDownloadArrayToAttachmentDto(downArray));
      });
  }

  public AttachmentThumbnailIdDownloadArrayToAttachmentDto(attachmentDownloadArrays) {
    return attachmentDownloadArrays.map((attachmentDownloadArray) => {
      if (attachmentDownloadArray["nativeURL"]) {
        attachmentDownloadArray["path"] = attachmentDownloadArray["nativeURL"];
        return new Attachment(attachmentDownloadArray);
      } else {
        return false;
      }
    });
  }

  public saveDownloadPath(path: {"nativeURL": string}) {
    let pathArray = [{path: path.nativeURL}];
    return this.syncUtilService.saveAttachment(this.AttachmentThumbnailIdDownloadArrayToAttachmentDto(pathArray));
  }

  fetchAttachmentsBySyncStatus(syncStatuses: Array<SyncStatus>): Observable<Array<Attachment>> {
    return this.curdService.observableFetchObjects(AttachmentDto, null, [{ syncStatus: syncStatuses }])
      .map(
        (attachmentDtos: Array<AttachmentDto>) => attachmentDtos
          .map((attachmentDto) => this.syncUtilService.toObjectFromDto(attachmentDto, Attachment))
      );
  }

  updateAttachmentById(attachment: Attachment, attachmentId: string): Observable<boolean> {
    let dto = this.syncUtilService.toObjectDto(attachment, AttachmentDto);
    return this.sqliteService.updateRow(dto, {id: attachmentId});
  }

}
